const application = require("../models/application")
const user = require("../models/userDetail")
const message = require("../models/message")

var express = require('express');
var router = express.Router();

const formidable = require('formidable');

//返回图片
router.post('/', (req, res, next) => {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        } else {
            if (fields.ok === 1) {
                user.updateOne({
                    UUID: fields.UUID
                }, {
                        $set: {
                            userGroup: fields.userGroup
                        }
                    }, (err) => {
                        if (err) {
                            res.json({ 'state': false, 'msg': err });
                        } else {
                            message.create({
                                UUID: fields.UUID,
                                target: fields.userGroup,
                                result: 1,
                                type: 'application',
                                status: 'unread'
                            }, (err) => {
                                if (err) {
                                    console.log(err)
                                }
                                application.remove({
                                    _id: fields._id
                                }, (error) => {
                                    if (error) {
                                        console.log(error)
                                    }
                                    res.json({ 'state': true });
                                })
                            })

                        }
                    })
            } else if (fields.ok === 0) {
                message.create({
                    UUID: fields.UUID,
                    target: fields.userGroup,
                    type: 'application',
                    result: 0,
                    status: 'unread'
                }, (err) => {
                    if (err) {
                        console.log(err)
                    }
                    application.remove({
                        _id: fields._id
                    }, (error) => {
                        if (error) {
                            console.log(error)
                        }
                        res.json({ 'state': true });
                    })
                })
            }


        }

    });

});

module.exports = router;